package lock.reentrantLock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 描述：TODO
 */

public class NonfairBargeDemo {
    private static final ReentrantReadWriteLock reentrantReadWriteLock
            = new ReentrantReadWriteLock(true);// 公平锁，不允许插队
    private static final ReentrantReadWriteLock.ReadLock readLock
            = reentrantReadWriteLock.readLock();
    private static final ReentrantReadWriteLock.WriteLock writeLock
            = reentrantReadWriteLock.writeLock();
    private static void read() {
        System.out.println(Thread.currentThread().getName() + "尝试获取读锁");
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "得到了读锁，正在读取");
            Thread.sleep(3000);
            System.out.println(Thread.currentThread().getName() + "读取完毕，释放读锁");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
    }
    private static void write() {
        System.out.println(Thread.currentThread().getName() + "尝试获取写锁");
        writeLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "得到了写锁，正在写入");
            Thread.sleep(3000);
            System.out.println(Thread.currentThread().getName() + "写入完毕，释放写锁");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }

    public static void main(String[] args) {
        new Thread(NonfairBargeDemo::write).start();
        new Thread(NonfairBargeDemo::read).start();
        new Thread(NonfairBargeDemo::read).start();
        new Thread(NonfairBargeDemo::write).start();
        new Thread(NonfairBargeDemo::read).start();
        new Thread(() -> {
                Thread[] threads = new Thread[1000];
                for (int i = 0; i < threads.length; i++) {
                    new Thread(NonfairBargeDemo::read, "子线程创建的线程" + i).start();
                }
        }).start();
    }
}
